﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StoragePeriod.Common;
using StoragePeriod.Data;

namespace StoragePeriod.Web.SysManage
{
    public partial class RoleManage : SecurityPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
                BindTree();
        }

        private void BindTree()
        {
            TreeNode rootNode = new TreeNode() { 
                Text="全部角色"
            };
            Role.All().ToList().ForEach(p => {
                rootNode.ChildNodes.Add(new TreeNode()
                {
                    Text = p.RoleName,
                    Value = p.RoleCode
                });
            });

            tvRoleView.Nodes.Add(rootNode);
        }

        protected void tvRoleView_SelectedNodeChanged(object sender, EventArgs e)
        {
            LoadRoleUserAndprivilege(tvRoleView.SelectedNode.Value);
            hdRoleCode.Value = tvRoleView.SelectedNode.Value;
        }

        private void LoadRoleUserAndprivilege(string p)
        {
            gvRoleprivilegeView.DataSource = RolePrivileges.Where("RoleCode==@0", p);
            gvRoleprivilegeView.DataBind();

            gvRoleUserView.DataSource = RoleUsers.Where("RoleCode==@0", p);
            gvRoleUserView.DataBind();
        }

        protected void gvprivilegeView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            RolePrivileges.Delete("PrivCode==@0 and RoleCode=@1", e.Keys[0].EToString(), e.Keys[1].EToString());
            
            Page.Alert(string.Format("权限：{0} 删除成功",e.Values[1].EToString()));
        }

        protected void gvRoleUserView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            RoleUsers.Delete("UserCode==@0 and RoleCode=@1", e.Keys[0].EToString(), e.Keys[1].EToString());

            Page.Alert(string.Format("用户：{0} 删除成功", e.Keys[0].EToString()));
        }

        protected void gvRoleprivilegeView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            (sender as GridView).PageIndex = e.NewPageIndex;
            LoadRoleUserAndprivilege(tvRoleView.SelectedNode.Value);            
        }
 
    }
}